﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Swift;
using SCM;

public class CardManager : Component
{
    public const int DrawCardCost = 1;

    public override void Init()
    {
        var sp = GameCore.Instance.Get<ServerPort>();
        sp.OnMessage("AddCoins", OnAddCoins);
        sp.OnMessage("AddUnits", OnAddUnits);
        sp.OnMessage("AddCards", OnAddCards);
    }

    // 抽一张卡
    public void RequestDrawCard(Action<bool, string> cb)
    {
        var conn = GameCore.Instance.ServerConnection;
        var buff = conn.Request2Srv("DrawCard", (data) =>
        {
            var ok = data.ReadBool();
            string c = null;
            if (ok)
            {
                var meInfo = GameCore.Instance.MeInfo;
                c = data.ReadString();
                meInfo.Coins -= DrawCardCost;
                meInfo.AddCard(c, 1);
            }

            cb.SC(ok, c);
        });
        conn.End(buff);
    }

    // 合成或升级单位
    public void RequestCombineOrUpgrade(string c, Action<bool> cb)
    {
        var conn = GameCore.Instance.ServerConnection;
        var buff = conn.Request2Srv("CombineOrUpgradeUnit", (data) =>
        {
            var ok = data.ReadBool();

            if (ok)
                GameCore.Instance.MeInfo.CombineOrUpgradeUnit(c);

            cb.SC(ok);
        });
        buff.Write(c);
        conn.End(buff);
    }

    // 服务器通知加金币
    public void OnAddCoins(IReadableBuffer data)
    {
        var num = data.ReadInt();
        GameCore.Instance.MeInfo.Coins += num;
    }

    // 解锁单位
    public void OnAddUnits(IReadableBuffer data)
    {
        var meInfo = GameCore.Instance.MeInfo;
        var uArr = data.ReadStringArr();
        foreach (var u in uArr)
            meInfo.AddUnit(u, 1);
    }

    // 增加卡片
    public void OnAddCards(IReadableBuffer data)
    {
        var meInfo = GameCore.Instance.MeInfo;
        var c = data.ReadString();
        var num = data.ReadInt();
        meInfo.AddCard(c, num);
    }
}
